/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controlador;

import controlador.exceptions.IllegalOrphanException;
import controlador.exceptions.NonexistentEntityException;
import entidad.Cliente;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import entidad.Deuda;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

/**
 *
 * @author a
 */
public class ClienteJpaController implements Serializable {

    public ClienteJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Cliente cliente) {
        if (cliente.getDeudaCollection() == null) {
            cliente.setDeudaCollection(new ArrayList<Deuda>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Collection<Deuda> attachedDeudaCollection = new ArrayList<Deuda>();
            for (Deuda deudaCollectionDeudaToAttach : cliente.getDeudaCollection()) {
                deudaCollectionDeudaToAttach = em.getReference(deudaCollectionDeudaToAttach.getClass(), deudaCollectionDeudaToAttach.getIdDeuda());
                attachedDeudaCollection.add(deudaCollectionDeudaToAttach);
            }
            cliente.setDeudaCollection(attachedDeudaCollection);
            em.persist(cliente);
            for (Deuda deudaCollectionDeuda : cliente.getDeudaCollection()) {
                Cliente oldClienteidClienteOfDeudaCollectionDeuda = deudaCollectionDeuda.getClienteidCliente();
                deudaCollectionDeuda.setClienteidCliente(cliente);
                deudaCollectionDeuda = em.merge(deudaCollectionDeuda);
                if (oldClienteidClienteOfDeudaCollectionDeuda != null) {
                    oldClienteidClienteOfDeudaCollectionDeuda.getDeudaCollection().remove(deudaCollectionDeuda);
                    oldClienteidClienteOfDeudaCollectionDeuda = em.merge(oldClienteidClienteOfDeudaCollectionDeuda);
                }
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Cliente cliente) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Cliente persistentCliente = em.find(Cliente.class, cliente.getIdCliente());
            Collection<Deuda> deudaCollectionOld = persistentCliente.getDeudaCollection();
            Collection<Deuda> deudaCollectionNew = cliente.getDeudaCollection();
            List<String> illegalOrphanMessages = null;
            for (Deuda deudaCollectionOldDeuda : deudaCollectionOld) {
                if (!deudaCollectionNew.contains(deudaCollectionOldDeuda)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Deuda " + deudaCollectionOldDeuda + " since its clienteidCliente field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Collection<Deuda> attachedDeudaCollectionNew = new ArrayList<Deuda>();
            for (Deuda deudaCollectionNewDeudaToAttach : deudaCollectionNew) {
                deudaCollectionNewDeudaToAttach = em.getReference(deudaCollectionNewDeudaToAttach.getClass(), deudaCollectionNewDeudaToAttach.getIdDeuda());
                attachedDeudaCollectionNew.add(deudaCollectionNewDeudaToAttach);
            }
            deudaCollectionNew = attachedDeudaCollectionNew;
            cliente.setDeudaCollection(deudaCollectionNew);
            cliente = em.merge(cliente);
            for (Deuda deudaCollectionNewDeuda : deudaCollectionNew) {
                if (!deudaCollectionOld.contains(deudaCollectionNewDeuda)) {
                    Cliente oldClienteidClienteOfDeudaCollectionNewDeuda = deudaCollectionNewDeuda.getClienteidCliente();
                    deudaCollectionNewDeuda.setClienteidCliente(cliente);
                    deudaCollectionNewDeuda = em.merge(deudaCollectionNewDeuda);
                    if (oldClienteidClienteOfDeudaCollectionNewDeuda != null && !oldClienteidClienteOfDeudaCollectionNewDeuda.equals(cliente)) {
                        oldClienteidClienteOfDeudaCollectionNewDeuda.getDeudaCollection().remove(deudaCollectionNewDeuda);
                        oldClienteidClienteOfDeudaCollectionNewDeuda = em.merge(oldClienteidClienteOfDeudaCollectionNewDeuda);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = cliente.getIdCliente();
                if (findCliente(id) == null) {
                    throw new NonexistentEntityException("The cliente with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Cliente cliente;
            try {
                cliente = em.getReference(Cliente.class, id);
                cliente.getIdCliente();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The cliente with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<Deuda> deudaCollectionOrphanCheck = cliente.getDeudaCollection();
            for (Deuda deudaCollectionOrphanCheckDeuda : deudaCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Cliente (" + cliente + ") cannot be destroyed since the Deuda " + deudaCollectionOrphanCheckDeuda + " in its deudaCollection field has a non-nullable clienteidCliente field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(cliente);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Cliente> findClienteEntities() {
        return findClienteEntities(true, -1, -1);
    }

    public List<Cliente> findClienteEntities(int maxResults, int firstResult) {
        return findClienteEntities(false, maxResults, firstResult);
    }

    private List<Cliente> findClienteEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Cliente.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Cliente findCliente(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Cliente.class, id);
        } finally {
            em.close();
        }
    }

    public int getClienteCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Cliente> rt = cq.from(Cliente.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
